package com.gonsin.gview.logic.controller;

import com.gonsin.base.ResponseResult;
import com.gonsin.base.exceptions.MyException;
import com.gonsin.gview.logic.services.download.DownloadManager;
import com.gonsin.gview.model.menu.GViewMenu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RestController
@ApiIgnore
@Api(tags = "模板接口")
@RequestMapping("/api/s11/gview/download")
public class GViewDownloadController {

    /**
     * 下载管理器
     */
    @Autowired private DownloadManager downloadManager;


    /**
     * 下载临时对象
     */
    @ApiIgnore
    @ApiOperation("菜单 - 获取内置所有菜单")
    @GetMapping("{downloadId}/{name}")
    public void getMenuViews(HttpServletRequest request,
                             HttpServletResponse response, @PathVariable("downloadId") String downloadId) throws IOException {

        try {
            Object item = downloadManager.getDownloadItem(downloadId);
            if(item instanceof File){
                downloadFile(request, response, (File)item);
                return;
            }

            if(item instanceof String){
                downloadString(request, response, (String)item);
                return;
            }

            if(item instanceof InputStream){
                downloadInputStream(request, response, (InputStream)item);
                return;
            }
        } finally {
            downloadManager.removeDownloadItem(downloadId);
        }
    }


    /**
     * 文件下载
     */
    private void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
        ServletContext context = request.getServletContext();
        String mimeType = context.getMimeType(file.getAbsolutePath());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
        response.setHeader(headerKey, headerValue);
        InputStream myStream = Files.newInputStream(Paths.get(file.getAbsolutePath()));
        try {
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } finally {
            if(myStream != null){
                myStream.close();
            }
        }
    }


    /**
     * 下载纯字符串
     */
    private void downloadString(HttpServletRequest request, HttpServletResponse response, String text) throws IOException {
        ServletContext context = request.getServletContext();
        String mimeType = context.getMimeType(request.getRequestURL().toString());
        if (mimeType == null) {
            mimeType = "application/json";
        }
        response.setContentType(mimeType);
        byte[] buffer = text.getBytes(StandardCharsets.UTF_8);
        response.setContentLength((int) buffer.length);
        String headerKey = "Content-Disposition";
        String filename = FilenameUtils.getName(request.getRequestURL().toString());
        String headerValue = String.format("attachment; filename=\"%s\"", filename);
        response.setHeader(headerKey, headerValue);
        InputStream myStream = new ByteArrayInputStream(buffer);
        try {
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } finally {
            if(myStream != null){
                myStream.close();
            }
        }
    }


    /**
     * 下载字节流
     */
    private void downloadInputStream(HttpServletRequest request, HttpServletResponse response, InputStream inputStream) throws IOException {
        ServletContext context = request.getServletContext();
        String mimeType = context.getMimeType(request.getRequestURL().toString());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        response.setContentType(mimeType);
        response.setContentLength((int) inputStream.available());
        String headerKey = "Content-Disposition";
        String filename = FilenameUtils.getName(request.getRequestURL().toString());
        String headerValue = String.format("attachment; filename=\"%s\"", filename);
        response.setHeader(headerKey, headerValue);
//        InputStream myStream = Files.newInputStream(Paths.get(file.getAbsolutePath()));
        try {
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } finally {
            if(inputStream != null){
                inputStream.close();
            }
        }
    }



}
